package com.heima.search.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 陈辉
 * @data 2023 16:09
 */
@Component
public class ApUserTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 解析请求头，拿到userId
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            ApUserThreadLocalUtil.setUser(userId);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ApUserThreadLocalUtil.clear();
    }
}
